package com.huamoxi.aop;

import com.huamoxi.consts.RedisConst;
import com.huamoxi.consts.ResponseConst;
import com.huamoxi.entity.User;
import com.huamoxi.utils.CacheUtil;
import com.huamoxi.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(2)
public class RepeatSubmitAspect {

    @Resource
    private CacheUtil cacheUtil;

    @Value("${login.repeat-login-submit}")
    private Long interval;

    @Around("@annotation(com.huamoxi.annotation.RepeatSubmitRequest) || @within(com.huamoxi.annotation.RepeatSubmitRequest)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取目标方法的参数
        Object[] args = joinPoint.getArgs();
        String account = null;

        // 遍历参数数组
        for (Object arg : args) {
            if (arg instanceof User user) {
                // 如果参数是 User 类型，获取 account 属性
                account = user.getAccount();
            }
        }

        Object obj = cacheUtil.get(RedisConst.REQUEST_LOGIN_NO_REPEAT + account);
        if (obj != null) {
            return ResultUtil.fail(ResponseConst.ERR_LOGIN_REPEAT);
        } else {
            cacheUtil.set(RedisConst.REQUEST_LOGIN_NO_REPEAT + account, 1, interval);
            // 执行目标方法
            return joinPoint.proceed();
        }
    }
}
